{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符串的基本操作\n",
    "\n",
    "所有标准序列操作（索引、切片、乘法、成员资格检查、长度、最小值和最大值）都适用于字符串，但别忘了字符串是不可变的，因此所有的元素赋值和切片赋值都是非法的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-1-3e219c690972>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mwebsite\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'http://www.python.org'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mwebsite\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'com'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "website = 'http://www.python.org'\n",
    "website[-3:] = 'com'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 设置字符串格式\n",
    "\n",
    "### 精减版"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello, world, Hot enough for ya?'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "format = \"Hello, %s, %s enough for ya?\"\n",
    "values = ('world', 'Hot')\n",
    "format % values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上述格式字符串中的%s称为转换说明符，指出了要将值插入什么地方。 s意味着将值视为字\n",
    "符串进行格式设置。如果指定的值不是字符串，将使用str将其转换为字符串。其他说明符将导\n",
    "致其他形式的转换。例如， %.3f将值的格式设置为包含3位小数的浮点"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可能遇到的另一种解决方案是所谓的模板字符串。它使用类似于UNIX shell的语法，旨在简化基本的格式\n",
    "设置机制，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello, Mars! Dusty enough for ya?'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from string import Template\n",
    "tmpl = Template(\"Hello, $who! $what enough for ya?\")\n",
    "tmpl.substitute(who=\"Mars\", what=\"Dusty\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "包含等号的参数称为关键字参数`!`在字符串格式设置中，可将关键字参数视为一种向命名替换字段提供值的方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "编写新代码时，应选择使用字符串方法`format`，它融合并强化了早期方法的优点。使用这种\n",
    "方法时，每个替换字段都用花括号括起，其中可能包含名称，还可能包含有关如何对相应的值进\n",
    "行转换和格式设置的信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "在最简单的情况下，替换字段没有名称或将索引用作名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'first, second and third'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{}, {} and {}\".format(\"first\", \"second\", \"third\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'first, second and third'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{0}, {1} and {2}\".format(\"first\", \"second\", \"third\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "然而，索引无需像上面这样按顺序排列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'to be or not to be'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{3} {0} {2} {1} {3} {0}\".format(\"be\",\"not\", \"or\", \"to\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "命名字段的工作原理与你预期的完全相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pi is appproximately 3.14.'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import pi\n",
    "\n",
    "\"{name} is appproximately {value:.2f}.\".format(value=pi, name=\"pi\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "当然，关键字参数的排列顺序无关紧要。在这里，我还指定了格式说明符.2f，并使用冒号\n",
    "将其与字段名隔开。它意味着要使用包含2位小数的浮点数格式。如果没有指定.2f，结果将如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pi is approximately 3.141592653589793.'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{name} is approximately {value}.\".format(value=pi, name=\"pi\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当然，关键字参数的排列顺序无关紧要。在这里，我还指定了格式说明符`.2f`，并使用冒号\n",
    "将其与字段名隔开。它意味着要使用包含2位小数的浮点数格式。如果没有指定.2f，结果将如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Euler's constant is roughly 2.718281828459045\""
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import e\n",
    "\n",
    "f\"Euler's constant is roughly {e}\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里，创建最终的字符串时，将把替换字段e替换为变量e的值。这与下面这个更明确一些\n",
    "的表达式等价："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Euler's constant is roughly 2.718281828459045.\""
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Euler's constant is roughly {e}.\".format(e=e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 完整版"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里的基本思想是对字符串调用方法format，并提供要设置其格式的值。字符串包含有关如何设置格式的信息，而这些信息是使用一种微型格式指定语言（ mini-language）指定的。每个值都被插入字符串中，以替换用花括号括起的**替换字段** 。要在最终结果中包含花括号，可在格式字符串中使用两个花括号（即{{或}}）来指定"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{ceci n'net pas une replacement field}\""
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{{ceci n'net pas une replacement field}}\".format()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在格式字符串中，最激动人心的部分为替换字段。替换字段由如下部分组成，其中每个部分\n",
    "都是可选的。\n",
    "\n",
    "- **字段名**: 索引或标识符，指出要设置哪个值的格式并使用结果来替换该字段。除指定值\n",
    "外，还可指定值的特定部分，如列表的元;\n",
    "- **转换标志**: 跟在叹号后面的单个字符。当前支持的字符包括r（表示repr）、 s（表示str）和a（表示ascii）。如果你指定了转换标志，将不使用对象本身的格式设置机制，而是使用指定的函数将对象转换为字符串，再做进一步的格式设置;\n",
    "- **格式说明符**: 跟在冒号后面的表达式（这种表达式是使用微型格式指定语言表示的）。格式说明符让我们能够详细地指定最终的格式，包括格式类型（如字符串、浮点数或十六\n",
    "进制数），字段宽度和数的精度，如何显示符号和千位分隔符，以及各种对齐和填充方式。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 替换字段名\n",
    "\n",
    "在最简单的情况下，只需向format提供要设置其格式的未命名参数，并在格式字符串中使用\n",
    "未命名字段。此时，将按顺序将字段和参数配对。你还可给参数指定名称，这种参数将被用于相\n",
    "应的替换字段中。你可混合使用这两种方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3 1 4 2'"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{foo} {} {bar} {}\".format(1, 2, bar=4, foo=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还可通过索引来指定要在哪个字段中使用相应的未命名参数，这样可不按顺序使用未命名参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3 2 4 1'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{foo} {1} {bar} {0}\".format(1, 2, bar=4, foo=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然而，不能同时使用手工编号和自动编号，因为这样很快会变得混乱不堪。\n",
    "你并非只能使用提供的值本身，而是可访问其组成部分（就像在常规Python代码中一样），\n",
    "如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Mr Smoketoomuch'"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fullname = ['Alfred', 'Smoketoomuch']\n",
    "\"Mr {name[1]}\".format(name=fullname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The math module defines the value 3.141592653589793 for pi'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "tmpl = \"The {mod.__name__} module defines the value {mod.pi} for pi\"\n",
    "tmpl.format(mod=math)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如你所见，可使用索引，还可使用句点表示法来访问导入的模块中的方法、属性、变量和函\n",
    "数（看起来很怪异的变量`__name__`包含指定模块的名称）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 基本转换"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "指定要在字段中包含的值后，就可添加有关如何设置其格式的指令了。首先，可以提供一个转换标志"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Π 'Π' '\\u03a0'\n"
     ]
    }
   ],
   "source": [
    "print(\"{pi!s} {pi!r} {pi!a}\".format(pi=\"Π\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上述三个标志（ s、 r和a）指定分别使用str、 repr和ascii进行转换。函数str通常创建外观\n",
    "普通的字符串版本（这里没有对输入字符串做任何处理）。函数repr尝试创建给定值的Python表示（这里是一个字符串字面量）。函数ascii创建只包含ASCII字符的表示，类似于Python 2中的repr。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你还可指定要转换的值是哪种类型，更准确地说，是要将其视为哪种类型。例如，你可能提\n",
    "供一个整数，但将其作为小数进行处理。为此可在格式说明（即冒号后面）使用字符f（表示定\n",
    "点数）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The number is 42'"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"The number is {num}\".format(num=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The number is 42.000000'"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"The number is {num:f}\".format(num=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The number is 101010'"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"The number is {num:b}\".format(num=42)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| 类型 | 含义 |\n",
    "| :-- | :---- |\n",
    "| b | 将整数表示为二进制数 |\n",
    "| c | 将整数解读为Unicode码点 |\n",
    "| d | 将整数视为十进制数进行处理，这是整数默认使用的说明符 |\n",
    "| e | 使用科学表示法来表示小数（用e来表示指数）|\n",
    "| E | 与e相同，但使用E来表示指数 |\n",
    "| f | 将小数表示为定点数 |\n",
    "| F | 与f相同，但对于特殊值（ nan和inf），使用大写表示 |\n",
    "| g | 自动在定点表示法和科学表示法之间做出选择。这是默认用于小数的说明符，但在默认情况下至少有1位小数 |\n",
    "| G | 与g相同，但使用大写来表示指数和特殊值 |\n",
    "| n | 与g相同，但插入随区域而异的数字分隔符 |\n",
    "| o | 将整数表示为八进制数 |\n",
    "| s | 保持字符串的格式不变，这是默认用于字符串的说明符 |\n",
    "| x | 将整数表示为十六进制数并使用小写字母 |\n",
    "| X | 与x相同，但使用大写字母 |\n",
    "| % | 将数表示为百分比值（乘以100，按说明符f设置格式，再在后面加上%）|"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 宽度、精度和千分位分隔符"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "设置浮点数（或其他更具体的小数类型）的格式时，默认在小数点后面显示6位小数，并根\n",
    "据需要设置字段的宽度，而不进行任何形式的填充。当然，这种默认设置可能不是你想要的，在这种情况下，可根据需要在格式说明中指定宽度和精度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'         3'"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{num:10}\".format(num=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Bob       '"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{name:10}\".format(name=\"Bob\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如你所见，数和字符串的对齐方式不同。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "精度也是使用整数指定的，但需要在它前面加上一个表示小数点的句点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pi day is 3.14'"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Pi day is {pi:.2f}\".format(pi=pi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里显式地指定了类型f，因为默认的精度处理方式稍有不同.当然，可同时指定宽度和精度."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'      3.14'"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{pi:10.2f}\".format(pi=pi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实际上，对于其他类型也可指定精度，但是这样做的情形不太常."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Guido'"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:.5}\".format(\"Guido van Rossum\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可使用逗号来指出你要添加千位分隔符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'One google is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'One google is {:,}'.format(10**100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同时指定其他格式设置元素时，这个逗号应放在宽度和表示精度的句点之间"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 符合、对齐和用0填充"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在一栏中同时包含字符串和数时，你可能想修改默认对齐方式。在指定宽度和精度的数前面，可添加一个标志。这个标志可以是零、加号、减号或空格，其中零表示使用0来填充数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0000003.14'"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:010.2f}\".format(pi) # 2位精度，10个宽度, 用0填充"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要指定左对齐、右对齐和居中，可分别使用<、 >和^。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.14      \n",
      "   3.14   \n",
      "      3.14\n"
     ]
    }
   ],
   "source": [
    "# 2个精度, 10个宽度, 左对齐，居中，右对齐\n",
    "print(\"{0:<10.2f}\\n{0:^10.2f}\\n{0:10.2f}\".format(pi))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用填充字符来扩充对齐说明符，这样将使用指定的字符而不是默认的空格来填充"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'$$$$WIN BIG$$$$'"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 15个宽度、居中、$填充\n",
    "\"{:$^15}\".format(\"WIN BIG\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还有更具体的说明符=，它指定将填充字符放在符号和数字之间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      3.14\n",
      "     -3.14\n"
     ]
    }
   ],
   "source": [
    "# 浮点、2位精度、10个宽度、索引指定\n",
    "print(\"{0:10.2f}\\n{1:10.2f}\".format(pi, -pi))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      3.14\n",
      "-     3.14\n"
     ]
    }
   ],
   "source": [
    "# 浮点、2位精度、10个宽度、填充字符放在符合和数字之间、索引指定\n",
    "print(\"{0:10.2f}\\n{1:=10.2f}\".format(pi, -pi))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果要给正数加上符号，可使用说明符+（将其放在对齐说明符后面），而不是默认的-"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.1\n",
      "-3.1\n"
     ]
    }
   ],
   "source": [
    "print(\"{0:-.2}\\n{1:-.2}\".format(pi, -pi)) # 默认设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+3.1\n",
      "-3.1\n"
     ]
    }
   ],
   "source": [
    "print(\"{0:+.2}\\n{1:+.2}\".format(pi, -pi))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果将符号说明符指定为空格，会在正数前面加上空格而不是+"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 3.1\n",
      "-3.1\n"
     ]
    }
   ],
   "source": [
    "print(\"{0: .2}\\n{1: .2}\".format(pi, -pi))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "需要介绍的最后一个要素是井号（ #）选项，你可将其放在符号说明符和宽度之间（如果指\n",
    "定了这两种设置）。这个选项将触发另一种转换方式，转换细节随类型而异。例如，对于二进制、八进制和十六进制转换，将加上一个前缀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'101010'"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:b}\".format(42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b101010'"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:#b}\".format(42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "对于各种十进制数，它要求必须包含小数点（对于类型g，它保留小数点后面的零）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'42'"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:g}\".format(42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'42.0000'"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{:#g}\".format(42)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在代码清单3-1所示的示例中，我分两次设置了字符串的格式，其中第一次旨在插入最终将\n",
    "作为格式说明符的字段宽度。这是因为这些信息是由用户提供的，我无法以硬编码的方式指定字段宽度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{:25}{:>10}'"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'{{:{}}}{{:>{}}}'.format(25, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{:25} {:>10.2f}'"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{{:{}}} {{:>{}.2f}}\".format(25, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Please enter width: 35\n",
      "===================================\n",
      "Item                          Price\n",
      "-----------------------------------\n",
      "Apples                         0.40\n",
      "Pears                          0.50\n",
      "Cantaloupes                    1.92\n",
      "Dried Apricots (16 oz.)        8.00\n",
      "Prunes (4 lbs.)               12.00\n",
      "===================================\n"
     ]
    }
   ],
   "source": [
    "# 根据指定的宽度打印格式良好的价格列表\n",
    "width = int(input('Please enter width: '))\n",
    "price_width = 10\n",
    "item_width = width - price_width\n",
    "header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)\n",
    "fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)\n",
    "\n",
    "print('=' * width)\n",
    "print(header_fmt.format('Item', 'Price'))\n",
    "print('-' * width)\n",
    "print(fmt.format('Apples', 0.4))\n",
    "print(fmt.format('Pears', 0.5))\n",
    "print(fmt.format('Cantaloupes', 1.92))\n",
    "print(fmt.format('Dried Apricots (16 oz.)', 8))\n",
    "print(fmt.format('Prunes (4 lbs.)', 12))\n",
    "print('=' * width)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{:25}{:>10}'"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## 字符串方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "前面介绍了列表的方法，而字符串的方法要多得多，因为其很多方法都是从模块string那里\n",
    "“继承”而来的。\n",
    "\n",
    "- center\n",
    "- find\n",
    "- join\n",
    "- lower\n",
    "- replace\n",
    "- split\n",
    "- strip\n",
    "- translate\n",
    "- 判断字符串是否满足特定条件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### center\n",
    "\n",
    "方法center通过在两边添加填充字符（默认为空格）让字符串居中。\n",
    "\n",
    "相关函数\n",
    "\n",
    "1. ljust\n",
    "2. rjust\n",
    "3. zfill"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'     The Middle by Jimmy Eat World     '"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"The Middle by Jimmy Eat World\".center(39)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'*****The Middle by Jimmy Eat World*****'"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"The Middle by Jimmy Eat World\".center(39, \"*\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### find\n",
    "\n",
    "方法find在字符串中查找子串。如果找到，就返回子串的第一个字符的索引，否则返回-1。\n",
    "\n",
    "相关函数:\n",
    "    \n",
    "1. rfind\n",
    "2. index\n",
    "3. rindex\n",
    "4. count\n",
    "5. startswith\n",
    "6. endswith"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"With a moo-moo here, and a moo-moo there\".find(\"moo\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "title = \"Monty Python's Flying Circus\"\n",
    "title.find(\"Monty\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "title.find(\"Python\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "title.find(\"Zirquss\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在垃圾邮件过滤器中检查主题是否包含'$$$'。这种检查也可使用find来执行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subject = '$$$ Get rich now!!! $$$'\n",
    "subject.find('$$$')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你还可指定搜索的起点和终点（它们都是可选的）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subject.find(\"$$$\", 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subject.find(\"!!!\", 0, 16)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，起点和终点值（第二个和第三个参数）指定的搜索范围包含起点，但不包含终点。这是Python惯常的做法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### join\n",
    "\n",
    "join是一个非常重要的字符串方法，其作用与split相反，用于合并序列的元素。\n",
    "\n",
    "相关函数:\n",
    "\n",
    "1. split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "sequence item 0: expected str instance, int found",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-95-a420c2a10e8d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mseq\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m4\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0msep\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'+'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0msep\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mjoin\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mseq\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#尝试合并一个数字列表\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: sequence item 0: expected str instance, int found"
     ]
    }
   ],
   "source": [
    "seq = [1, 2, 3, 4, 5]\n",
    "sep = '+'\n",
    "sep.join(seq) #尝试合并一个数字列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1+2+3+4+5'"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "seq = ['1', '2', '3', '4', '5']\n",
    "sep = '+'\n",
    "sep.join(seq) #尝试合并一个字符串列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'/usr/bin/env'"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dirs = '', 'usr', 'bin', 'env'\n",
    "'/'.join(dirs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C:\\usr\\bin\\env\n"
     ]
    }
   ],
   "source": [
    "print('C:' + '\\\\'.join(dirs))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如你所见，所合并序列的元素必须都是字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### lower\n",
    "\n",
    "方法lower返回字符串的小写版本。\n",
    "\n",
    "相关函数:\n",
    "    \n",
    "1. islower\n",
    "2. istitle\n",
    "3. isupper\n",
    "4. translate\n",
    "5. capitalize\n",
    "6. casefold\n",
    "7. swapcase\n",
    "8. title\n",
    "9. upper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'tondheim hammer dance'"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'Tondheim Hammer Dance'.lower()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "假设你要检查列表中是否包含指定的用户名。如果列表包含字符串'gumby'，而指定的用户\n",
    "名为'Gumby'，你将找不到它。当然，如果列表包含'Gumby'，而指定的用户名为'gumby'或'GUMBY'，结果同样找不到。对于这种问题，一种解决方案是在存储和搜索时，将所有的用户名都转换为小写。这样做的代码类似于下面这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found it!\n"
     ]
    }
   ],
   "source": [
    "name = \"Gumby\"\n",
    "names = ['gumby', 'smith', 'jones']\n",
    "if name.lower() in names:\n",
    "    print('Found it!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个与lower相关的方法是title。它将字符串转换为词首大写，即所有单词的首字母都大写，其他字母都小写。然而，它确定单词边界的方式可能导致结果不合理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"That'S All, Folks\""
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"that's all, folks\".title()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "另一种方法是使用模块string中的函数capwords:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"That's All, Folks!\""
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import string\n",
    "string.capwords(\"that's all, folks!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### replace\n",
    "\n",
    "方法replace将指定子串都替换为另一个字符串，并返回替换后的结果\n",
    "\n",
    "相关函数:\n",
    "\n",
    "1. translate\n",
    "2. expandtabs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Thees ees a test'"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"This is a test\".replace(\"is\", \"ees\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你使用过字处理程序的“查找并替换”功能，一定知道这个方法很有用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### split\n",
    "\n",
    "split是一个非常重要的字符串方法，其作用与join相反，用于将字符串拆分为序列\n",
    "\n",
    "相关函数:\n",
    "\n",
    "1. join\n",
    "2. partition\n",
    "3. rpartition\n",
    "4. rsplit\n",
    "5. splitlines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1', '2', '3', '4', '5']"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"1+2+3+4+5\".split(\"+\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['', 'usr', 'bin', 'env']"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"/usr/bin/env\".split(\"/\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Using', 'the', 'default']"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Using the default\".split()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，如果没有指定分隔符，将默认在单个或多个连续的空白字符（空格、制表符、换行符\n",
    "等）处进行拆分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### strip\n",
    "\n",
    "方法strip将字符串开头和末尾的空白（但不包括中间的空白）删除，并返回删除后的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'internal whitespace is kept'"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"     internal whitespace is kept   \".strip()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "与lower一样，需要将输入与存储的值进行比较时， strip很有用。回到前面介绍lower时使用\n",
    "的用户名示例，并假定用户输入用户名时不小心在末尾加上了一个空格。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = ['gumby', 'smith', 'jones']\n",
    "name = 'gumby '\n",
    "\n",
    "if name in names:\n",
    "    print(\"Found it!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found it\n"
     ]
    }
   ],
   "source": [
    "if name.strip() in names:\n",
    "    print(\"Found it\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你还可在一个字符串参数中指定要删除哪些字符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' SPAM * for * everyone!!! '"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"*** SPAM * for * everyone!!! ***\".strip(\"*!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个方法只删除开头或末尾的指定字符，因此中间的星号未被删除"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### translate\n",
    "\n",
    "相关函数:\n",
    "\n",
    "1. replace\n",
    "2. lower"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "方法translate与replace一样替换字符串的特定部分，但不同的是它只能进行单字符替换。\n",
    "这个方法的优势在于能够同时替换多个字符，因此效率比replace高。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个方法的用途很多（如替换换行符或其他随平台而异的特殊字符），但这里只介绍一个比\n",
    "较简单（也有点傻）的示例。假设你要将一段英语文本转换为带有德国口音的版本，为此必须将字符c和s分别替换为k和"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然而，使用translate前必须创建一个转换表。这个转换表指出了不同Unicode码点之间的转\n",
    "换关系。要创建转换表，可对字符串类型str调用方法maketrans，这个方法接受两个参数：两个长度相同的字符串，它们指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符。就这个简单的示例而言，代码类似于下面这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{99: 107, 115: 122}"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table = str.maketrans('cs', 'kz')\n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'thiz iz an inkredible tezt'"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'this is an incredible test'.translate(table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调用方法maketrans时，还可提供可选的第三个参数，指定要将哪些字母删除。例如，要模\n",
    "仿语速极快的德国口音，可将所有的空格都删除"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'thizizaninkredibletezt'"
      ]
     },
     "execution_count": 116,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table = str.maketrans('cs', 'kz', ' ')\n",
    "\"this is an incredible test\".translate(table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 判断字符串是否满足特定的条件\n",
    "\n",
    "很多字符串方法都以is打头，如isspace、 isdigit和isupper，它们判断字符串是否具有特定\n",
    "的性质（如包含的字符全为空白、数字或大写）。如果字符串具备特定的性质，这些方法就返回\n",
    "True，否则返回False。\n",
    "\n",
    "相关函数: isalnum、 isalpha、 isdecimal、 isdigit、 isidentifier、 islower、 isnumeric、\n",
    "isprintable、 isspace、 istitle、 isupper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
